<?php
/**
 * Created by PhpStorm.
 * User: surface
 * Date: 2019/1/11
 * Time: 20:07
 */

namespace app\Manage\controller;
use app\common\controller\Manage;
use app\common\model\Order;
use app\common\model\RoomBooking as RoomBookingModel;
use Request;
use think\Db;

class BillTurnover extends Manage
{

    public function billTurnover()
    {
        $data = input();
        $date_time = [];
        if(!empty($data['date'])) {
            $date_time[] = strtotime($data['date'][0].' 00:00:00');
            $date_time[] = strtotime($data['date'][1].' 23:59:59');
        } else {
            $date_time[] = strtotime(date('Y-m-d 00:00:00', time()-6*86400));
            $date_time[] = strtotime(date('Y-m-d 23:59:59', time()));
        }
        //
        $order_condition = [];
        $order_condition[] = ['ctime', 'between', [$date_time[0], $date_time[1]]];
        $order_condition[] = ['status', '=', 2];
        $order_field = ['SUM(order_amount)' => 'total_amount', "FROM_UNIXTIME(ctime, '%Y-%m-%d')" => 'days'];
        $order_model = new \app\common\model\Order();
        $order_group = $order_model
            ->where($order_condition)
            ->group('days')
            ->field($order_field)
            ->select();
        $order_group = arr_key($order_group, 'days');
        //
        $field = ['SUM(price)' => 'total_price', "FROM_UNIXTIME(ctime, '%Y-%m-%d')" => 'days'];
        $condition = [];
        $condition[] = ['pay_status', '=', 1];
        $condition[] = ['ctime', 'between', [$date_time[0], $date_time[1]]];
        $taocn_group = Db::name('taocan_order')
                ->where($condition)
                ->group('days')
                ->field($field)
                ->select();
        $taocn_group = arr_key($taocn_group, 'days');
        //获取时间
        $day_num = ceil(($date_time[1]-$date_time[0])/86400);
        $total_turnover = [
            'total_turnover' => 0,
            'total_order' => 0,
            'total_taocan' => 0
        ];
        $turnover = [];
        for($i=0;  $day_num > $i; $day_num--) {
            $days = date('Y-m-d', $date_time[0]+($day_num-1)*86400);
            $turnover[$days]['order_amount'] = !empty($order_group[$days]['total_amount'])? $order_group[$days]['total_amount']: 0;
            $turnover[$days]['taocan_amount'] = !empty($taocn_group[$days]['total_price'])? $taocn_group[$days]['total_price']: 0;
            $turnover[$days]['total'] =  $turnover[$days]['order_amount']  + $turnover[$days]['taocan_amount'];
            $total_turnover['total_turnover'] += $turnover[$days]['total'];
            $total_turnover['total_order'] += $turnover[$days]['order_amount'];
            $total_turnover['total_taocan'] += $turnover[$days]['taocan_amount'];
        }
        $this->assign('turnover', $turnover);
        $this->assign('total_turnover', $total_turnover);
        return $this->fetch('index');
    }
}